import Notify from '@vant/weapp/notify/notify';

// 导入promise请求
import http from '../../utils/http_promise.js';

// 1 导入验证插件;
import WxValidate from '../../utils/WxValidate.js';

// pages/create_house/create_house.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    'fileList':[],
     'uploadedImgs':[],
     formData:{}
  },
   
  afterRead(e){
     
     // 实现图片预览
     this.setData({
       fileList:e.detail.file
     })
     
     //console.log(this.data.fileList);
      
  },

  // 表单提交
  onSubmit(e){

    // 表单校验
    let params = e.detail.value;

    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];

      // wx.showModal({
      //   title: '提示信息',
      //   content: error.msg
      // });

      Notify({ type: 'danger', message: error.msg });

      return false
    }
    
    this.data.formData = e.detail.value;
    this.upload();

  },
  
  upload(){

    // promise 对象的数组;  [promise1,promise2,promise3]
    let res = [];

    this.data.fileList.map((item,index)=>{
      
      //console.log(item.path,index);
      
      // promise 对象;
      res[index] = new Promise((resolve, reject)=>{
        
        // 单张图片上传;
        wx.uploadFile({ 

          url: 'http://127.0.0.1/jinqi_api/public/index.php/api/house/upload',
          filePath: item.path,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success:(res)=> {

             resolve(res);          
             this.data.uploadedImgs.push(res.data);
             
          }

        })

      })
      

    })
    
    // 处理图片上传完成逻辑
    Promise.all([...res]).then((result) => {
      
      this.data.formData.imgs = this.data.uploadedImgs.join('&');
      console.log(this.data.formData);

      let that = this;
      
      // 保存房源信息
      http.request({
         'method':"POST",
          requireAuth:true,
          "url":"house/store",
          "data":this.data.formData
      })
      .then(res=>{
        
         if(res.data.status == 200){
             wx.navigateTo({
               url: '/pages/my_houses/my_houses'
             })
         }
         
      })
      
     
    }).catch((error) => {

      console.log('err')

    })
    
   
  },

  onLoad(){

    // 3 调用验证规则初始化方法
    this.initValidate();

  },

  onShow(){

    // 验证是否登录
     http.checkLogin();

  },


  // 2 定义验证规则
  initValidate() {

    // 验证规则
    const rules = {

      tel: {
        tel:true,
        required: true
      }
      
    }

    // 提示信息
    const messages = {
      tel: {
        tel: "请输入正确手机号码!",
        required:"手机号码不能为空!"
      }

    }

    // 自定义验证规则
    this.WxValidate = new WxValidate(rules, messages);
    
  }

  
})